package com.basic.ui.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

/**
 * @author Peter Liu
 * @since 2023/8/7 18:52
 *
 */
open class BaseBottomSheetFragment :
    BottomSheetDialogFragment() {

    private var mPeekHeight = 0
    private var mMaxHeight = 0
    private var mBottomSheetBehavior: BottomSheetBehavior<*>? = null

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
        mBottomSheetBehavior = dialog.behavior
        initDialog(dialog)
        return dialog
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog?.window?.let {
            initWindow(it)
        }
        initView()
        initModel()
    }

    open fun initWindow(window: Window) {
        window.apply {
            if (mMaxHeight > 0) {
                setLayout(ViewGroup.LayoutParams.MATCH_PARENT, mMaxHeight)
            }
            setGravity(Gravity.BOTTOM)
        }
    }

    open fun initDialog(dialog: BottomSheetDialog) {
        initPeekHeight()
    }

    open fun initPeekHeight() {
        if (mPeekHeight <= 0) {
            return
        }
        mBottomSheetBehavior?.peekHeight = mPeekHeight
    }

    open fun initView() {

    }

    open fun initModel() {

    }

    open fun setPeekHeight(peekHeight: Int) {
        mPeekHeight = peekHeight
    }

    open fun setMaxHeight(height: Int) {
        mMaxHeight = height
    }

    override fun show(manager: FragmentManager, tag: String?) {
        super.show(manager, javaClass.name)
    }

    fun show(activity: FragmentActivity) {
        show(activity.supportFragmentManager, null)
    }

    fun show(fragment: Fragment) {
        show(fragment.childFragmentManager, null)
    }

}